﻿//
// Created by francklinson on 2021/3/25.
//
// queue.cpp -- Queue and Customer methods

#include "Queue.h"

#include <cstdlib>           // (or stdlib.h) for rand()


Queue::Queue(int qs) : qsize(qs)
{
    front = rear = nullptr;   // 初始化 首尾指针都指向空指针
    items = 0;  // 队列长度为0
}

Queue::~Queue()
{
    Node *temp; // 新建临时节点
    while (front != nullptr)    // while queue is not yet empty
    {
        temp = front;        // save address of front item
        front = front->next; // reset pointer to next item
        delete temp;         // delete former front
    }
}

bool Queue::isEmpty() const
{
    return items == 0;
}

bool Queue::isFull() const
{
    return items == qsize;
}

int Queue::queueCount() const
{
    return items;
}

bool Queue::enQueue(const Item &item)
{
    if (isFull())
        return false;
    Node *add = new Node; // create node . if failure, new throws std::bad_alloc exception
    add->item = item;      // set node pointers
    add->next = nullptr;      // or nullptr;
    items++; // 队列长度+1
    if (front == nullptr)     // if queue is empty, 原队列是空的
        front = add;       // place item at front
    else
        rear->next = add;  // 原来队尾节点指向新节点
    rear = add;            // 新节点变成新队尾
    return true;
}

bool Queue::deQueue(Item &item)
{
    if (front == nullptr)
        return false;
    item = front->item;  // set item to first item in queue
    items--;
    Node *temp = front; // save location of first item
    front = front->next; // reset front to next item
    delete temp;         // delete former first item
    if (items == 0)
        rear = nullptr;
    return true;
}

// customer method

// when is the time at which the customer arrives
// the arrival time is set to when and the processing
// time set to a random value in the range 1 - 3
void Customer::set(long when)
{
    processTime = std::rand() % 3 + 1;
    arrive = when;
}